package com.lanling.redis.client.connection;


import com.lanling.redis.client.protocol.Protocol;
import com.lanling.redis.client.util.SafeEncoder;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @date ：Created in 2021/11/23 9:34
 * @description：传输层
 * @author：lanling
 */
public class Connection {
    private Socket socket;
    private String host;//ip
    private int port;//端口号
    private OutputStream outputStream;
    private InputStream inputStream;
    private boolean broken = false;//连接异常标识


    public Connection(String host, int port) {
        this.host = host;
        this.port = port;
    }

    /**
     *
     * 建立连接
     * @return
     */
    public Connection connection() {
        try {
            if (!isConnected()) {//连接不存在再建立连接
                socket = new Socket(host, port);
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();
            }
        } catch (IOException e) {
            e.printStackTrace();
            broken = true;
        } finally {
            if (broken == true && socket != null) {//连接异常关闭socket连接
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return this;
    }

    /**
     *
     * 发送数据和命令
     * @return
     */
    public Connection sendCommand( Protocol.Command command, byte[]... args) {
        connection();//建立连接
        Protocol.sendCommand(outputStream, command,args);

        return this;
    }

    /**
     * 获取响应信息
     * @return
     */
    public String getStatusCodeReply(){
        byte[] bytes = new byte[1024];
        try {
            socket.getInputStream().read(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SafeEncoder.encode(bytes);
    }

    /**
     * 获取key信息
     * @return
     */
    public String getBulkReply(){
        byte[] bytes = new byte[1024];
        try {
            socket.getInputStream().read(bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return SafeEncoder.encode(bytes);
    }

    /**
     *
     * 判断连接是否存在，存在 false  不存在 true
     * @return
     */
    public boolean isConnected() {
        return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected()
                && !socket.isInputShutdown() && !socket.isOutputShutdown();
    }
}
